/*
 * Copyright (C) 2016 Baidu, Inc. All Rights Reserved.
 */
package me.cuilei.springbootdemo.common;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import me.cuilei.springbootdemo.user.UserNotFoundException;

/**
 * Created by cuilei05 on 16/9/30.
 */
@ControllerAdvice
public class ExceptionControllerAdvice extends ResponseEntityExceptionHandler {

    // 定义全局异常处理，value属性可以过滤拦截条件，此处拦截所有的Exception
    @ExceptionHandler(value = Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Response exception(Exception exception, WebRequest request) {
        exception.printStackTrace();
        return new Response(0, "系统错误!");
    }

    @ExceptionHandler(UserNotFoundException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    Response handleControllerException(HttpServletRequest request, Throwable ex) {
        Response response = new Response(1, ex.getMessage());
        return response;
    }
}
